/*
掘金 https://juejin.cn/
功能：全自动签到，粘福，免费抽奖；
配合云函数或青龙面板定时执行实现每天无需操作全自动；
变量：juejin_cookie  填写ck
* cron: 8 9 * * * 掘金.js
* const $ = new Env("掘金");
*/

const axios = require('axios');

// 判断是否为Node.js环境并动态引入通知模块
let sendNotify;
try {
  if (typeof process !== 'undefined' && process.versions && process.versions.node) {
    // Node.js环境，动态引入本地通知模块
    sendNotify = require('./sendNotify');
    console.log('已加载本地通知模块');
  }
} catch (error) {
  console.log('通知模块加载失败，将继续执行但不发送通知:', error.message);
}

// 自定义通知标题
const notifyTitle = "掘金";

juejin_cookie = process.env.juejin_cookie
let $axios = axios.create({
  withCredentials: true,
  timeout: 30000, //超时时间
  baseURL: "https://api.juejin.cn/growth_api/v1/",
  headers: {
    'Accept': 'application/json',
    'cookie': juejin_cookie
  }
})

const _http = (options) => {
  let {
    url,
    method = 'get',
    params = {}
  } = options;
  return new Promise((resolve, reject) => {
    $axios({
      method,
      url,
      params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      resolve(false)
    })
  })
}

const apis = {
  verifyTodayStatus: {
    url: '/get_today_status',
    method: 'get',
    description: '获取今天是否签到'
  },
  checkIn: {
    url: '/check_in',
    method: 'post',
    description: '开始签到'
  },
  getSignInfo: {
    url: '/get_counts',
    method: 'get',
    description: '获取签到天数状态'
  },
  getPointCount: {
    url: '/get_cur_point',
    method: 'get',
    description: '获取当前矿石数'
  },
  getLuckyInfo: {
    url: '/lottery_lucky/my_lucky',
    method: 'post',
    description: '获取幸运抽奖我的状态'
  },
  getFreeCount: {
    url: '/lottery_config/get',
    method: 'get',
    description: '获取免费次数'
  },
  dipLucky: {
    url: '/lottery_lucky/dip_lucky',
    method: 'post',
    description: '沾喜气',
    params: {
      lottery_history_id: '7090346718260101131'
    }
  },
  startLottery: {
    url: '/lottery/draw',
    method: 'post',
    description: '开始抽奖'
  },
}

// 发送通知的函数
const sendNotification = (title, content) => {
  if (sendNotify && typeof sendNotify.sendNotify === 'function') {
    try {
      sendNotify.sendNotify(title, content);
      console.log('通知发送成功');
    } catch (error) {
      console.log('通知发送失败:', error.message);
    }
  } else {
    console.log('通知功能不可用，跳过发送通知');
  }
}

const check_in_juejin = async () => {
  let finalResult = {
    checkInStatus: false,
    continuousDay: 0,
    totalDay: 0,
    oreCount: 0,
    prize: '',
    LuckyValue: 0,
    dipLuckySuccess: false
  }
  
  let res_verifyTodayStatus = await _http(apis.verifyTodayStatus);
  if (res_verifyTodayStatus && res_verifyTodayStatus.err_no != 0) {
    const errorMsg = '掘金脚本失败，可能需要更新cookie!';
    console.log(errorMsg);
    sendNotification(notifyTitle, errorMsg);
    return;
  }
  
  if (res_verifyTodayStatus && !res_verifyTodayStatus.data) {
    let res_checkIn = await _http(apis.checkIn);
    if (res_checkIn && res_checkIn.err_no == 0) {
      finalResult.checkInStatus = true;
      console.log('签到成功');
    } else {
      console.log('签到失败');
    }
  } else {
    finalResult.checkInStatus = true;
    console.log('今日已签到');
  }

  // 沾喜气
  let dipResult = await _http(apis.dipLucky);
  if (dipResult && dipResult.err_no === 0) {
    finalResult.dipLuckySuccess = true;
    console.log('沾喜气成功');
  } else {
    console.log('沾喜气失败');
  }
  
  // 抽奖逻辑
  let res_getFreeCount = await _http(apis.getFreeCount);
  if (res_getFreeCount && res_getFreeCount.data && res_getFreeCount.data.free_count != 0) {
    let res_startLottery = await _http(apis.startLottery);
    if (res_startLottery && res_startLottery.err_no == 0) {
      finalResult.prize = res_startLottery.data.lottery_name;
      console.log(`抽奖成功，获得: ${finalResult.prize}`);
    } else {
      console.log('抽奖失败');
    }
  } else {
    finalResult.prize = null;
    console.log('今日无免费抽奖次数');
  }
  
  // 获取用户信息
  let temp_user_info = await Promise.all([_http(apis.getSignInfo), _http(apis.getPointCount), _http(apis.getLuckyInfo)]);
  let [res_getSignInfo, res_getPointCount, res_getLuckyInfo] = [...temp_user_info];
  
  if (res_getPointCount && res_getPointCount.data !== undefined) {
    finalResult.oreCount = res_getPointCount.data;
  }
  
  if (res_getSignInfo && res_getSignInfo.data) {
    finalResult.continuousDay = res_getSignInfo.data.cont_count;
    finalResult.totalDay = res_getSignInfo.data.sum_count;
  }
  
  if (res_getLuckyInfo && res_getLuckyInfo.data) {
    finalResult.LuckyValue = res_getLuckyInfo.data.total_value;
  }
  
  // 构建通知内容
  let text = `稀土掘金签到结果：
✅ 今日签到${finalResult.checkInStatus ? '成功' : '失败'}
📅 连续签到: ${finalResult.continuousDay} 天
📊 累计签到: ${finalResult.totalDay} 天
⛏️ 当前矿石: ${finalResult.oreCount} 个
${finalResult.dipLuckySuccess ? '🎉 沾喜气成功' : '❌ 沾喜气失败'}
${finalResult.prize ? `🎁 抽中奖品: ${finalResult.prize}` : '📭 今日无免费抽奖次数'}
🍀 幸运值: ${finalResult.LuckyValue}/6000`;
  
  console.log(text);
  
  // 发送通知
  sendNotification(notifyTitle, text);
}

check_in_juejin();